<?php 
/****

	If you want the best of the world,
give the world your best anytime！
            				——不二
                							
****/

defined('ACCESS')||exit('Forbidden!');
//顶层模型类
class Model {
	protected $prefix;//表前缀
	protected $db;
	protected $tablename;
	protected $field = array();//所有字段集合
	protected $pk;//主键

	public function __construct(){
		$this->prefix = $GLOBALS['config']['mysql']['prefix'];//表前缀
		$this->tablename = $this->prefix . $this->tablename;//真实表名称

		//连接数据库
		$this->db = Mysql::getInstance();

		//获取表格字段集合和主键
		$this->getField();
	}

	//获取表格字段集合和主键
	public function getField(){
		$sql = 'desc '.$this->tablename;
		$res = $this->db->getAll($sql);
		foreach ($res as $key => $value) {
			$this->field[] = $value['Field'];
			if($value['Key'] == 'PRI'){
				$this->pk = $value['Field'];
			}
		}
	}

	//根据主键自动查询
	public function find($id = 0){
		$sql = 'select * from '.$this->tablename.' where '.$this->pk.'='.$id;
		return $this->db->getRow($sql);
	}

	//根据条件进行查询
	public function select($where = 1){
		$sql = 'select * from '.$this->tablename.' where '.$where;
		return $this->db->getAll($sql);
	}

	//根据主键自动删除
	public function delete($id){
		$sql = 'delete from '.$this->tablename.' where '.$this->pk.'='.$id;
		return $this->db->query($sql);
	}

	//根据条件删除
	public function deleteAll($where = 0){
		$sql = 'delete from '.$this->tablename.' where '.$where;
		return $this->db->query($sql);
	}

	//过滤掉不存在的字段
	public function filter($data){
		//过滤掉不存在的字段
		foreach ($data as $key => $value) {
			if(!in_array($key, $this->field)){
				unset($data[$key]);
			}
		}
		return $data;
	}

	//自动插入
	public function insert($data){
		$data = $this->filter($data);

		//执行插入
		$key = array_keys($data);
		$value = array_values($data);
		//平凑sql语句
		$sql = 'insert into '.$this->tablename . '(';
		$sql .= implode(',', $key) . ') values (\'';
		$sql .= implode("','", $value) . '\')';

		return $this->db->query($sql);
	}

	//基于主键自动更新
	public function update($data){
		$data = $this->filter($data);

		$id = $data[$this->pk];
		unset($data[$this->pk]);

		$sql = 'update '.$this->tablename . ' set ';
		foreach ($data as $key => $value) {
			$sql .= $key.'=\''.$value.'\',';
		}
		$sql = rtrim($sql,',');
		$sql .= ' where '.$this->pk . '='. $id;

		//执行更新操作
		return $this->db->query($sql);
	}

	//分页
	public function getPages($cnt,$where = 1,$curr = 1){
		//当前页码$curr = 1
		//每页显示条数 $cnt
		//总数 $num
		$sql = 'select count(1) from '. $this->tablename .' where '.$where ;
		$num = $this->db->getOne($sql);
		if($num == 0){
			return false;
		}

		//页数
		$n = ceil($num/$cnt);
		//最左,最右侧·························只显示上一页，当前页和下一页
		$left = max(1,$curr-1);
		$right = min($left+2,$n);
		$left = max(1,$right-2);

		for($a = $left;$a <= $right;$a++){
			$_GET['page'] = $a;
			$page[$a] = http_build_query($_GET);
		}
		return $page;
	}
}

